import TauActionPanel from '@/components/TauActionPanel';
import TauPage from '@/components/TauPage';
import TauTable from '@/components/TauTable';
import { useStore } from '@/hooks';
import { Tab } from '@alifd/next';
import { t } from '@lingui/macro';
import { uniqueId } from 'lodash';
import React, { useEffect, useState } from 'react';
import { ENUMS, column, toSelectDataSource } from './stores/definitions';
import { observer } from 'mobx-react-lite';
import TotalPriceBar from './components/totalPriceBar';

const tableId = uniqueId('tauTable-');

function parseRegion(dictItem) {
  if (!dictItem) return {};
  const { fullId } = dictItem;
  const s = fullId?.split(':', 2);
  return { main: s[0], minor: s[1] };
}

const tabItems = [
  { key: 'ticket', label: t`中港通专线及巴士车票报表统计` },
  { key: 'order', label: t`包车订单报表统计` },
];

const OrderReport = () => {
  const { orderReportStore: store } = useStore();
  const [tabKey, setTabKey] = useState(toJS(store._tabKey));

  useEffect(() => {
    (async () => {
      store.fetchCompaniesOptions();
      store.getCompanyDriver();
    })();
  }, []);

  // 获取列表数据
  const handleOnSearch = (params) => {
    const { orderDate, getOnDate, startStations, endStations, startRegion: ingorn1, endRegion: ingorn2, refundStatus, refundDate, ...searchArgs } = params.values;
    const { startRegion, endRegion } = params.valueObjects;
    const [from, to] = orderDate || [];
    const [fromTime, toTime] = getOnDate || [];
    const [fromRefundTime, toRefundTime] = refundDate || [];


    const { main: startMainArea, minor: startMinorArea } = parseRegion(startRegion);
    const { main: endMainArea, minor: endMinorArea } = parseRegion(endRegion);

    const stationsValue = {
      ticket: {
        start: startStations && [startStations],
        end: endStations && [endStations],
      },
      order: {
        start: startMainArea && [startMainArea, startMinorArea],
        end: endMainArea && [endMainArea, endMinorArea],
      },
    };
    store.search = {
      from,
      to,
      fromTime,
      toTime,
      fromRefundTime,
      toRefundTime,
      refundStatus: refundStatus && Number(refundStatus),
      startStations: stationsValue[store.tabKey].start,
      endStations: stationsValue[store.tabKey].end,
      ...searchArgs,
    };
  };

  // 获取不同选择器站点选择
  const getStationSelector = () => {
    switch (tabKey) {
      case 'ticket': return [
        {
          name: 'startStations',
          type: 'bus-station',
          props: {
            placeholder: [t`始发站点`],
            changeOnSelect: true,
            style: { minWidth: '160px' },
          },
        },
        {
          name: 'endStations',
          type: 'bus-station',
          props: {
            placeholder: [t`结束站点`],
            changeOnSelect: true,
            style: { minWidth: '160px' },
          },
        },
        {
          name: 'ticketStates',
          type: 'select',
          props: {
            dataSource: toSelectDataSource(ENUMS.ticketStatus),
            placeholder: t`车票状态`,
            mode: 'multiple',
          },
        },
      ];
      case 'order': return [
        { // 字典tree级联选择
          name: 'startRegion',
          type: 'dict-tree',
          props: { placeholder: t`始发区域`, changeOnSelect: true, dictId: 'region', maxLevel: 2, style: { minWidth: '160px' } },
        },
        {
          name: 'endRegion',
          type: 'dict-tree',
          props: { placeholder: t`结束区域`, changeOnSelect: true, dictId: 'region', maxLevel: 2, style: { minWidth: '160px' } },
        },
        { // 字典项下拉列表
          name: 'orderStatus',
          type: 'dict-item',
          props: {
            placeholder: t`订单状态`,
            dataSource: toSelectDataSource(ENUMS.orderStatus),
            mode: 'multiple',
          },
        },
        {
          name: 'companyId',
          type: 'select',
          props: {
            placeholder: t`承运商`,
            dictId: 'company',
            dataSource: toJS(store.companyOptions),
            style: { width: 200 },
          },
          onChange: (v) => { store.getCompanyDriver(v); },
        },
        {
          name: 'driverId',
          type: 'select',
          props: {
            placeholder: t`司机`,
            dataSource: toJS(store.driverOptions),
            style: { width: 200 },
          },
        },
      ];
      default: [];
    }
  };

  // 获取不同的表格项
  const getColumns = () => {
    switch (tabKey) {
      case 'ticket': return [
        column('orderId', { width: 180 }),
        column('salesDate', { width: 124, sortable: true }),
        column('passengerName', { width: 58 }),
        column('ticketCode', { width: 180 }),
        column('isReturn', { width: 58 }),
        column('fromStation', { width: 180 }),
        column('toStation', { width: 180 }),
        column('shiftTime', { width: 124, sortable: true }),
        column('operatingState', { width: 58 }),
        column('price', { width: 58 }),
        column('refundTime', { width: 124 }),
        column('refundPrice', { width: 58 }),
        column('profit', { width: 100 }),
        column('remark', { width: 58 }),
      ];
      case 'order': return [
        column('orderId', { width: 180 }),
        column('salesDate', { width: 124, sortable: true }),
        column('shiftTime', { width: 124, sortable: true }),
        column('passengerName', { width: 58 }),
        column('fromStation', { width: 180 }),
        column('toStation', { width: 180 }),
        column('companyName', { width: 58 }),
        column('driverName', { width: 58 }),
        column('orderPrice', { width: 58 }),
        column('driverPrice', { width: 58 }),
        column('profit', { width: 100 }),
        column('orderState', { width: 58 }),
        column('refundPrice', { width: 58 }),
        column('remark', { width: 58 }),
      ];
      default: [];
    }
  };

  // 导出报表
  const exportReport = async () => {
    const fileName = {
      ticket: '中港通专线及巴士车票报表统计报表',
      order: '包车订单统计报表',
    };
    store.export(fileName[tabKey]);
  };

  return (
    <TauPage className="page-container">
      <TauActionPanel
        onSearch={handleOnSearch}
        actions={[
          {
            name: 'btn-excelExport',
            title: t`表格导出`,
            type: 'primary',
            onClick: exportReport,
          },
        ]}
        searchItems={[
          {
            name: 'orderDate',
            type: 'date-range',
            props: {
              placeholder: [t`下单时间(开始)`, t`下单时间（结束)`],
            },
          },
          {
            name: 'getOnDate',
            type: 'date-range',
            props: {
              placeholder: [t`起始上车时间`, t`结束上车时间`],
            },
          },
          ...getStationSelector(),
          {
            name: 'refundStatus',
            type: 'select',
            props: {
              placeholder: t`退款状态`,
              dataSource: toSelectDataSource(ENUMS.refundStatus),
            },
          },
          {
            name: 'refundDate',
            type: 'date-range',
            props: {
              placeholder: [t`退票时间`],
            },
          },
        ]}
        keywordSearch={{
          placeholder: t`请输入关键字搜搜`,
        }}
        className="action-panel"
      />
      <TotalPriceBar type={tabKey} />
      <div className="content">
        <Tab
          activeKey={store.tabKey}
          onChange={(v) => {
            store.tabKey = v;
            setTabKey(v);
          }}
        >
          {tabItems.map((item) => (<Tab.Item key={item.key} title={item.label} />))}
        </Tab>
        <TauTable
          instanceId={tableId}
          primaryKey="idx"
          tableLayout="fixed"
          currentPage={store.pg.page}
          pageSize={store.pg.size}
          total={store.total}
          sort={store.tableSort}
          onFetch={(pg) => { store.pg = pg; }}
          loading={store.loading}
          dataSource={toJS(store.tableData)}
          columns={[
            { title: t`编号`, dataIndex: 'idx', width: 44, cell: (v, i) => store.idx(i) },
            ...getColumns(),
          ]}
        />
      </div>
    </TauPage>
  );
};

export default observer(OrderReport);
